let util = require("./utils/util.js")

// app.js
App({
  onLaunch() {
    let app = this;
    //初始化colorUI自定义的statusBar基础参数
    wx.getSystemInfo({
      success: e => {
        this.globalData.StatusBar = e.statusBarHeight;
        let custom = wx.getMenuButtonBoundingClientRect();
        this.globalData.Custom = custom;
        this.globalData.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
        this.globalData.screenHeight = e.screenHeight - this.globalData.CustomBar;
      }
    })

    if (util.SysConstParams.debug && wx.getStorageSync("debug_session_key") != undefined && wx.getStorageSync("debug_session_key")!="") {
      console.log("启用调试信息")
      app.globalData.NETWORK_OK = true;
      app.globalData.NETWORK_SECRET = true;
      app.globalData.HELLO_OK = true;
      util.SysConstParams.sessionKey = wx.getStorageSync("debug_session_key");
      util.SysConstParams.aesKey = wx.getStorageSync("debug_session_secret");
      console.log(util.SysConstParams.sessionKey)
      console.log(util.SysConstParams.aesKey)
    } else {
      // APP打开后完成后台会话密钥交换
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          util.secureInit(res.code, function (res) {
            app.globalData.NETWORK_OK = true;
            if(res.statusCode!='200'){
              app.globalData.SERVICE_OK = false;
              return;
            }
            app.globalData.SERVICE_OK = true;

            if(res.data["header"]["status_code"]=="000000"){
              app.globalData.HELLO_OK = true;
              let server_hi = util.aesDecrypt(res.data["body"]["server_hi"]);
              let session_key = server_hi.split("|")[0];
              let server_hi_mac = server_hi.split("|")[1];
              let local_session_hi_mac = util.sha256(session_key + util.SysConstParams.aesKey);
              if (local_session_hi_mac == server_hi_mac) {
                util.SysConstParams.sessionKey = session_key;
                app.globalData.NETWORK_SECRET = true;
                if (util.SysConstParams.debug) {
                  wx.setStorageSync("debug_session_key", session_key);
                  wx.setStorageSync("debug_session_secret", util.SysConstParams.aesKey);
                }
              } else {
                console.log("网络环境不安全");
                app.globalData.NETWORK_SECRET = false;
              }  
            }else{
              app.globalData.HELLO_OK = false;
            }
          }, function () {
            console.log("网络异常");
            app.globalData.NETWORK_OK = false;
          }
          );
        }
      })
    }
  },
  onShow: function () {
  },
  onHide: function(){
  },
  globalData: {
    userInfo: null
    // ,
    // HELLO_OK: false,//握手成功
    // SESSION_OK: false,//会话有效
    // NETWORK_OK: false//网络连通性
    // SERVICE_OK: false //服务正确性
  }
})
